#include "linkstack.h"
LinkStack *createLinkStack() {
    LinkStack *stack = (LinkStack *) malloc(sizeof(LinkStack));
    stack->count = 0;
    stack->top = NULL;
    return stack;
}

int pushLinkStack(LinkStack *stack, Element e) {
    // 1. 先有新节点
    StackNode *node = (StackNode *) malloc(sizeof(StackNode));
    node->data = e;
    // 2. 处理新节点的next
    node->next = stack->top;
    // 3. 调整top为新位置
    stack->top = node;
    ++stack->count;
    return 0;
}

int popLinkStack(LinkStack *stack, Element *e) {
    if (stack->top == NULL) {
        return -1;
    }
    // 1. 备份
    StackNode *tmp = stack->top;
    // 2. 把栈顶元素 赋值给 上层空间
    *e = stack->top->data;
    // 3. 调整节点的关系，间接的删除了栈顶元素
    stack->top = tmp->next;
    // 4. 释放栈顶元素节点的空间
    free(tmp);
    --stack->count;
    return 0;
}

void releaseLinkStack(LinkStack *stack) {
    if (stack) {
        // 释放栈中所有的元素
        StackNode *tmp;
        while (stack->top) {
            tmp = stack->top;
            stack->top = tmp->next;
            free(tmp);
            --stack->count;
        }
        printf("stack count: %d\n", stack->count);
        free(stack);
    }
}